package com.cloudcross.ssp.listener;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.cloudcross.ssp.common.AliYunOSSOperator;
import com.cloudcross.ssp.common.utils.HttpClienUtil;

/**
 * 阿里云上传初始化
 * @author wuqiang.du
 *
 */
public class UploadListener implements Runnable{
    
    private List<UrlStatus> lstUrls = new ArrayList<UrlStatus>();
    
    private  boolean running = false;
    
    private static UploadListener uploadListener = new UploadListener();
    
    private String urlPrefix = "http://img.adinall.com/dsp/";
    
    private UploadListener() {
    }
    
    public static UploadListener getInstance() {
        return uploadListener;
    }
    
    class UrlStatus {
        String imgUrl;
        String localUrl;
        boolean success = false;
        
        public UrlStatus(String imgUrl,String localUrl) {
            this.imgUrl = imgUrl;
            this.localUrl = localUrl;
        }
    }
    
    @Override
    public void run() {
        try {
            while (true) {
                if (lstUrls.size() > 0) {
                    syncAli();
                }
                Thread.sleep(1000);
            }
        } catch(Exception e) {
            
        }
    }
    
    public void addUrl(String url,String localUrl) {
        UrlStatus urlStatus = new UrlStatus(url,localUrl);
        lstUrls.add(urlStatus);
    }
   
    private void syncAli() {
        try {
            if (running) {
                return;
            }
            running = true;
            for (UrlStatus urlStatus : lstUrls) {
                saveAli(urlStatus);
            }
            for (int i = lstUrls.size() - 1; i >= 0; i--) {
                UrlStatus urlStatus = lstUrls.get(i);
                if (urlStatus.success) {
                    lstUrls.remove(i);
                }
            }
        } catch (Exception e) {
            
        } finally {
            running = false;
        }
    }
    
    private void saveAli(UrlStatus urlStatus) {
        String imgUrl = urlPrefix + urlStatus.imgUrl.replaceAll("\\\\", "/");
        AliYunOSSOperator.saveObject(urlStatus.imgUrl.replaceAll("\\\\", "/"),urlStatus.localUrl);
        String isExist = HttpClienUtil.doGet(imgUrl, null);
        //阿里云文件存在
        urlStatus.success = !StringUtils.isEmpty(isExist);
    }
}
